<?php
/**
 * Created by PhpStorm.
 * User: xueb
 * Date: 2016/12/20
 * Time: 上午11:36
 */

namespace App\Components;


use App\Constants\ApiReturnCode;

class HttpRequestResult
{
    protected $_head = null;
    protected $_content = null;
    protected $_statusCode = 200;

    public function __construct(array $map_Result){
        $this->_head = isset($map_Result['head']) ? $map_Result['head'] : null;
        $this->_statusCode = isset($map_Result['status_code']) ? $map_Result['status_code'] : 404;
        $this->_content = isset($map_Result['content']) ? $this->_statusCode == 200 ? json_decode($map_Result['content'],true) : $map_Result['content'] : null;
    }

    public function data($name){
        return isset($this->_content['data']) && isset($this->_content['data'][$name]) ?
            $this->_content['data'][$name] : null;
    }

    public function code(){
        return isset($this->_content['code']) ? $this->_content['code'] : ApiReturnCode::FAILED;
    }

    public function success(){
        return $this->code() == ApiReturnCode::SUCCESS;
    }

    public function message(){
        return isset($this->_content['message']) ? $this->_content['message'] : '';
    }

    public function getFailMessage(){
        if($this->_statusCode != 200){
            return '逻辑错误:' . $this->_statusCode . ' ' . $this->_content;
        }else{
            return '接口返回失败: Code:' . $this->code() . ' message:' . $this->message();
        }

    }

    public function __get($name){
        if($name == 'statusCode'){
            return $this->_statusCode;
        }
        if($name == 'code'){
            return $this->_content['code'];
        }
        if($name == 'success'){
            return $this->code == 1;
        }

        return $this->data($name);
    }

}